package cn.com.yxw.webapp.controller;

import cn.com.yxw.webapp.pojo.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by Administrator on 2015/4/9.
 */
@Controller
@RequestMapping("/")
public class MainController extends BaseController {

    static final Logger logger = LoggerFactory.getLogger(MainController.class);

    @RequestMapping("/loginPage")
    public String loginPage(Admin admin){

        return "login";
    }

    /**
     * 登录
     * @param admin
     * @return
     */
    @RequestMapping("/login")
    public String login(@ModelAttribute("admin") Admin admin, HttpServletRequest request){

        // 登录后跳转地址
        String successUrl = InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/main";
        String unauthorized = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/common/unauthorized.jsp";
        try {
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isAuthenticated()){
                UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
                // 登录认证。shiro框架自动调用ShiroDataBaseRealm.AuthenticationInfo 方法 验证用户名密码
                subject.login(token);
            }
        } catch (UnknownAccountException uae) {
            return unauthorized;
        } catch (IncorrectCredentialsException ice) {
            return unauthorized;
        } catch (LockedAccountException lae) {
            return unauthorized;
        } catch (AuthenticationException ae) {
            return unauthorized;
        }

        logger.info("登录成功 用户:" + getCurrentUser().getUsername() + "IP" + request.getRemoteAddr());
        return successUrl;
    }


    /**
     * 首页
     * @return
     */
    @RequestMapping("/main")
    public String  main(){
        System.out.println("sadfasdf");
        return "main";
    }
}
